import { createStore } from 'vuex'

export default createStore({
  state: {
    userInfo: {},
    isLogin: false,
    cartList: [],
    activeTabBar: 0
  },
  mutations: {
    SET_ACTIVE_TABBAR (state, index) {
      state.activeTabBar = index
      console.log('set active', state.activeTabBar)
    },
    SET_USER_INFO (state, userInfo) {
      state.userInfo = userInfo
    },
    LOGIN (state, val) {
      state.isLogin = val
    },
    ADD_CART_ITEM (state, val, type) {
      var nowCl = state.cartList
      var flag = false
      var flag0 = false
      console.log('vuex-val', val, type)
      for (var i = 0; i < nowCl.length; i++) {
        if (nowCl[i].storeid === val.storeid) {
          flag = true
          var item = nowCl[i].item
          for (var j = 0; j < item.length; j++) {
            if (item[j].goodsId === val.item[0].goodsId) {
              flag0 = true
              if (type === 1) {
                item[j].orderNum += 1
              }
              break
            }
          }
          if (!flag0) nowCl[i].item.push(val.item[0])
          break
        }
      }
      if (!flag) state.cartList.push(val)
    },
    REDUCE_CART_ITEM (state, val) {
      var nowCl = state.cartList
      for (var i = 0; i < nowCl.length; i++) {
        if (nowCl[i].storeid === val.storeid) {
          var item = nowCl[i].item
          for (var j = 0; j < item.length; j++) {
            if (item[j].goodsId === val.item.goodsId) {
              if (item[j].orderNum > 1) {
                item[j].orderNum -= 1
                break
              } else if (item[j].orderNum === 1) {
                console.log('equals 1')
                item = item.forEach(function (it, index, arr) {
                  if (it.goodsId === item[j].goodsId) {
                    arr.splice(index, 1)
                  }
                })
                break
              }
            }
          }
        }
      }
    },
    DEL_CART_ITEM (state, val) {

    }
  },
  getters: {
    cart_item_num: (state) => {
      var size = 0
      var nowCl = state.cartList
      for (var i = 0; i < nowCl.length; i++) {
        size += nowCl[i].item.length
      }
      return size
    },
    store_goods_list: (state) => (storeid) => {
      console.log('接收到', storeid)
      var nowCl = state.cartList
      for (var i = 0; i < nowCl.length; i++) {
        if (nowCl[i].storeid === storeid) {
          console.log('从店铺筛选')
          return nowCl[i].item
        }
      }
      return []
    }

  },
  actions: {},
  modules: {}
})
